package org.bysun.ggcip.http;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


/**
 * User: bysun
 * Date: 2014/6/7 0007
 * Time: 13:48
 */
public class Validator{

    private int timeout = 500;

    public Validator(int timeout) {
        this.timeout = timeout;
    }

    public void valid(IpDto dto){
        // 检查超时时间 超时直接抛弃
        try {
            dto.setConnTime(connectCast(dto.getIp()));
        } catch (IOException e) {
            return;
        }

        // 检查证书信息
        try {
            certValid(dto.getIp());
        } catch (IOException e) {
            return;
        }
        // 无异常走到这里证书校验通过
        dto.setUseful(true);
    }

    private long connectCast(String ip) throws IOException {
        URL url = new URL("http://" + ip);
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(timeout);
        long cast = System.currentTimeMillis();
        conn.connect();
        cast = System.currentTimeMillis() - cast;
        return cast;
    }

    private void certValid(String ip) throws IOException {
        URL url = new URL("https://" + ip);
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(timeout);
        conn.connect();
    }
}
